import auth from "@/plugins/auth";
import { constantRoutes } from "@/router";
import { getRouters } from "@/api/menu";
import { defineStore } from "pinia";

// 预加载所有views文件
const modules = import.meta.glob("@/views/**/*.vue");

// 动态导入views文件
const loadView = (view) => {
  console.log("🔍 尝试加载组件:", view);
  const cleanPath = view.startsWith("/") ? view.substring(1) : view;
  const finalPath = cleanPath.endsWith(".vue") ? cleanPath : `${cleanPath}.vue`;
  const fullPath = `/src/views/${finalPath}`;

  console.log("📁 组件路径:", fullPath);
  console.log("📦 可用模块:", Object.keys(modules).filter(key => key.includes(view)));

  if (modules[fullPath]) {
    console.log("✅ 组件找到:", fullPath);
    return modules[fullPath];
  } else {
    console.error("❌ Component not found:", fullPath);
    console.error("❌ Available modules:", Object.keys(modules));
    return () => import("@/views/error/404.vue");
  }
};

const usePermissionStore = defineStore("permission", {
  state: () => ({
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
  }),
  actions: {
    setRoutes(routes) {
      this.addRoutes = routes;
      this.routes = constantRoutes.concat(routes);
    },
    setDefaultRoutes(routes) {
      this.defaultRoutes = constantRoutes.concat(routes);
    },
    setTopbarRoutes(routes) {
      this.topbarRouters = routes;
    },
    setSidebarRouters(routes) {
      this.sidebarRouters = routes;
    },
    generateRoutes(roles) {
      return new Promise((resolve, reject) => {
        console.log("🚀 开始获取路由数据...");
        getRouters()
          .then((res) => {
            console.log("📡 路由接口返回数据:", res);
            const menuData = res.data;
            console.log("📋 菜单数据:", menuData);
            
            if (!menuData || !Array.isArray(menuData)) {
              console.error("❌ 菜单数据格式错误:", menuData);
              reject(new Error("菜单数据格式错误"));
              return;
            }
            
            // 1. 生成顶部导航菜单（第一层）
            const topbarRoutes = generateTopbarRoutes(menuData);
            console.log("🔝 顶部导航路由:", topbarRoutes);
            
            // 2. 生成侧边栏菜单（第二、三层）
            const sidebarRoutes = generateSidebarRoutes(menuData);
            console.log("📱 侧边栏路由:", sidebarRoutes);
            
            // 3. 生成实际的路由配置
            const actualRoutes = generateActualRoutes(menuData);
            console.log("🛣️ 实际路由配置:", actualRoutes);

            // 设置各种路由
            this.setRoutes(actualRoutes);
            this.setSidebarRouters(sidebarRoutes);
            this.setDefaultRoutes(sidebarRoutes);
            this.setTopbarRoutes(topbarRoutes);
            

            // 初始化时设置首页为默认选中，并显示其子菜单
            const homeMenu = topbarRoutes.find(menu => menu.path === '/home');
            if (homeMenu && homeMenu.children) {
              this.setSidebarRouters(homeMenu.children);
            }

            console.log("✅ 路由生成完成");
            resolve(actualRoutes);
          })
          .catch((error) => {
            console.error("❌ 路由生成失败:", error);
            reject(error);
          });
      });
    },
  },
});

// 生成顶部导航菜单（第一层菜单）
function generateTopbarRoutes(menuData) {
  return menuData.map(menu => ({
    name: menu.name,
    path: menu.path,
    meta: {
      title: menu.meta?.title || menu.name,
      icon: menu.meta?.icon || 'menu'
    },
    children: menu.children ? menu.children.map(secondLevel => {
      const secondRoute = {
        name: secondLevel.name,
        path: `${menu.path}/${secondLevel.path}`,
        component: secondLevel.component === 'ParentView' ? () => import('@/components/ParentView/index.vue') : loadView(secondLevel.component),
        meta: {
          title: secondLevel.meta?.title || secondLevel.name,
          icon: secondLevel.meta?.icon || 'menu'
        }
      };
      
      // 如果有第三层菜单
      if (secondLevel.children && secondLevel.children.length > 0) {
        secondRoute.children = secondLevel.children.map(thirdLevel => ({
          name: thirdLevel.name,
          path: `${menu.path}/${secondLevel.path}/${thirdLevel.path}`,
          component: loadView(thirdLevel.component),
          meta: {
            title: thirdLevel.meta?.title || thirdLevel.name,
            icon: thirdLevel.meta?.icon || 'menu'
          }
        }));
        
        // 为ParentView设置重定向
        if (secondLevel.component === 'ParentView') {
          secondRoute.redirect = `${menu.path}/${secondLevel.path}/${secondLevel.children[0].path}`;
        }
      }
      
      return secondRoute;
    }) : []
  }));
}

// 生成侧边栏菜单（第二、三层菜单）
// 注意：侧边栏菜单实际上是从 topbarRouters 中动态获取的，这里返回空数组
function generateSidebarRoutes(menuData) {
  return [];
}

// 生成实际的路由配置
function generateActualRoutes(menuData) {
  const routes = [];
  
  menuData.forEach(firstLevel => {
    // 第一层路由
    const firstRoute = {
      name: firstLevel.name,
      path: firstLevel.path,
      component: () => import('@/layout/index.vue'),
      meta: {
        title: firstLevel.meta?.title || firstLevel.name,
        icon: firstLevel.meta?.icon || 'menu'
      }
    };
    
    // 设置重定向到第一个子菜单
    if (firstLevel.children && firstLevel.children.length > 0) {
      const firstChild = firstLevel.children[0];
      if (firstChild.children && firstChild.children.length > 0) {
        // 特殊处理 analysis 路径
        if (firstLevel.path === '/analysis') {
          firstRoute.redirect = '/analysis/rdt/index';
        } else {
          // 使用相对路径，避免绝对路径问题
          firstRoute.redirect = `${firstChild.path}/${firstChild.children[0].path}`;
        }
      } else {
        firstRoute.redirect = firstChild.path;
      }
    }
    
    // 处理子路由
    if (firstLevel.children && firstLevel.children.length > 0) {
      firstRoute.children = [];
      
      firstLevel.children.forEach(secondLevel => {
        const secondRoute = {
          name: secondLevel.name,
          path: secondLevel.path, // 使用相对路径
          component: secondLevel.component === 'ParentView' ? () => import('@/components/ParentView/index.vue') : loadView(secondLevel.component),
          meta: {
            title: secondLevel.meta?.title || secondLevel.name,
            icon: secondLevel.meta?.icon || 'menu'
          }
        };
        
        // 如果有第三层菜单
        if (secondLevel.children && secondLevel.children.length > 0) {
          secondRoute.children = secondLevel.children.map(thirdLevel => ({
            name: thirdLevel.name,
            path: thirdLevel.path, // 使用相对路径
            component: loadView(thirdLevel.component),
            meta: {
              title: thirdLevel.meta?.title || thirdLevel.name,
              icon: thirdLevel.meta?.icon || 'menu'
            }
          }));
          
          // 为ParentView设置重定向
          if (secondLevel.component === 'ParentView') {
            secondRoute.redirect = secondLevel.children[0].path; // 使用相对路径
          }
        }
        
        firstRoute.children.push(secondRoute);
      });
    }
    
    routes.push(firstRoute);
  });
  
  return routes;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}

export default usePermissionStore;
